﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AlgoTest
{
    public class EventCriticalSection
    {
        private EventWaitHandle _event;

        public void Enter()
        {
            var newEvt = new ManualResetEvent(false);
            EventWaitHandle oldEvt = null;

            while ((oldEvt = Interlocked.CompareExchange(ref this._event, newEvt, null)) != null)
            {
                oldEvt.WaitOne();
            }
        }

        public void Exit()
        {
            var evt = this._event;

            if (evt != null)
            {
                evt.Set();
            }

            this._event = null;
        }
    }
}
